import { DictUnit } from "./trie"
import { MpSegment } from "./mpSegment"
import { PTMap, createObj } from "./utility"
import { Segment } from "./segment";


const POS_M = "m"
const POS_ENG = "eng"
const POS_X = "x"

export interface PosTagger {
    tag(str: string, seg: Segment): string[],

}

export function createPosTagger(): PosTagger {
    return {
        tag
    }

}

function tag(str: string, seg: Segment): string[] {

    let res: string[] = []
    let CutRes: string[] = seg.cut(str)

    for (let i = 0, itr: string; i < CutRes.length; i++) {
        itr = CutRes[i]
        let v = `${itr}:${lookunTag(itr, seg)}`
        res.push(v)
    }
    return res

}

function lookunTag(itr: string, seg: Segment): string {
    let tmp: DictUnit
    let runs: string = itr
    let dict = seg.getDictTrie()

    tmp = dict.getDictUnit(runs)
    if (!tmp) {
        return specialRule(runs)
    }
    else {
        return tmp.tag
    }
}


function specialRule(ch: string): string {
    let m = 0
    let eng = 0
    for (let i = 0; i < ch.length && eng < ch.length / 2; i++) {
        if (ch.charCodeAt(i) < 0x80) {
            eng++
            if ('0'.charCodeAt(0) <= ch.charCodeAt(i) && ch.charCodeAt(i) <= '9'.charCodeAt(0)) {
                m++
            }
        }
    }


    if (eng == 0) {
        return POS_X
    }

    if (m == eng) {
        return POS_M
    }

    return POS_ENG

}